package com.hb.trade.server.center.au.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hb.core.pojo.center.au.dto.OrgDeptDTO;
import com.hb.core.pojo.center.au.entity.OrgDept;
import com.hb.core.pojo.center.au.entity.User;
import com.hb.core.pojo.parent.MPBaseController;
import com.hb.core.pojo.parent.MPCommonEntity;
import com.hb.core.pojo.parent.PageResult;
import com.hb.trade.server.center.au.service.OrgDeptService;
import com.hb.trade.server.center.au.service.UserService;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.MsgUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 部门信息表 前端控制器
 * </p>
 *
 * @author zhaojk
 * @since 2021-11-29
 */
@RestController
public class OrgDeptController extends MPBaseController<OrgDept, OrgDeptService> {

    public OrgDeptController(OrgDeptService service) {
        super(service);
    }

    @Resource
    private UserService userService;

    /**
     * @param orgDept:
     * @Description: 分页查询部门列表
     * @Author: zhongdl
     * @Date:2022/1/20 14:52
     * @return: {@link Message <  PageResult <  OrgDeptDTO >> }
     **/
    @PostMapping("/orgDept/pageOrgDept")
    public Message<PageResult<OrgDeptDTO>> pageOrgDept(@RequestBody OrgDeptDTO orgDept) {

        PageResult<OrgDeptDTO> pageResult = service.pageOrgDept(orgDept);
        return MsgUtil.success(pageResult);
    }

    /**
     * @param orgDept:
     * @Description: 保存部门
     * @Author: zhongdl
     * @Date:2022/1/20 16:11
     * @return: {@link Message< Boolean> }
     **/
    @PostMapping("/orgDept/saveOrgDept")
    public Message<String> saveOrgDept(@RequestBody OrgDeptDTO orgDept) {
        String msg = orgDept.paramsValid("orgId");
        if (StrUtil.isNotEmpty(msg)) {
            return MsgUtil.fail(msg);
        }
        orgDept.setDeptName(orgDept.getDeptName().trim());
        //根据名称查询部门
        boolean repeatNameFlag = service.repeatNameFlag(orgDept.getDeptName().trim(), orgDept.getId(), orgDept.getOrgId());
        if (repeatNameFlag) {
            return MsgUtil.fail("当前企业的部门名称已经存在,请修改后重新保存");
        }
        boolean flag;
        if (orgDept.getId() == null) {
            orgDept.buildBaseData(1);
            flag = service.save(orgDept);
        } else {
            orgDept.buildBaseData(2);
            flag = service.updateById(orgDept);
        }
        return flag ? MsgUtil.success(orgDept.getId().toString()) : MsgUtil.fail("操作失败");
    }

    /**
     * @Description: 根据id查询部门详情
     * @Author: zhongdl
     * @Date:2022/1/20 16:24
     * @return: {@link Message< OrgDeptDTO> }
     **/
    @PostMapping("/orgDept/getOrgDeptId")
    public Message<OrgDeptDTO> getOrgDeptId(@RequestBody OrgDeptDTO orgDeptDTO) {
        OrgDept orgDept = service.getById(orgDeptDTO.getId());
        return MsgUtil.success(orgDept.to(OrgDeptDTO.class));
    }

    /**
     * @param userId:
     * @Description:根据用户id查询部门详情
     * @Author: zhongdl
     * @Date:2022/5/6 1:49
     * @return: {@link org.fzzn.core.model.msg.Message<com.hb.core.pojo.center.au.dto.OrgDeptDTO> }
     **/
    @PostMapping("/orgDept/getOrgDeptByUserId")
    public Message<OrgDeptDTO> getOrgDeptByUserId(@RequestParam Long userId){
        User user = userService.getById(userId);
        if (user == null){
            return MsgUtil.fail("用户信息不存在");
        }
        OrgDept orgDept = service.getById(user.getDeptId());
        if (orgDept == null){
            return MsgUtil.fail("部门信息不存在");
        }
        return MsgUtil.success(orgDept.to(OrgDeptDTO.class));

    }

    /**
     * @param orgDept:
     * @Description: 根据id删除部门
     * @Author: zhongdl
     * @Date:2022/1/20 16:32
     * @return: {@link Message< Boolean> }
     **/
    @PostMapping("/orgDept/removeById")
    public Message<Boolean> removeById(@RequestBody OrgDeptDTO orgDept) {
        if (orgDept.getId() == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        /*
         * zhanghu
         * 2022年3月4日
         * 先判断该部门下是否有用户，有则不能删除
         * 删除部门后，将该部门下所有的用户关联的部门id清空
         */
        Map<String, Object> map = new HashMap<>();
        map.put("dept_id", orgDept.getId());
        List<User> users = userService.listByMap(map);
        if (!users.isEmpty()) {
            return MsgUtil.fail("该部门下含有" + users.size() + "个员工，禁止删除");
        }
        orgDept.buildBaseData(3);
        boolean flag = service.updateById(orgDept);
        return MsgUtil.msg(flag);
    }

    /**
     * @param orgDept:
     * @Description: 查询企业部门列表
     * @Author: zhongdl
     * @Date:2022/2/14 8:47
     * @return: {@link Message< List< OrgDept>> }
     **/
    @PostMapping("/orgDept/listOrgDept")
    public Message<List<OrgDept>> listOrgDept(@RequestBody OrgDeptDTO orgDept) {
        QueryWrapper<OrgDept> wrapper = OrgDept.wrapper();
        wrapper.eq("od.org_id", orgDept.getOrgId());
        if (orgDept.getRoleSign() != null) {
            wrapper.last("and exists(select 1 from au_user u\n" +
                    "            left join au_user_role aur on u.id=aur.user_id\n" +
                    "            left join au_role r on aur.role_id=r.id\n" +
                    "            where r.role_sign=" + orgDept.getRoleSign() + " and od.create_id=u.id)");
        }
        List<OrgDept> list = service.listDept(wrapper);
        return MsgUtil.success(list);
    }

    /**
     * 查询指定用户用户所在部门下的所有用户
     *
     * @param userId
     * @return
     */
    @PostMapping("/orgDept/listUserIdsByWorkMate")
    public Message<List<Long>> listUserIdsByWorkMate(@RequestParam("userId") Long userId) {
        User user = userService.getById(userId);
        if (user == null || user.getDeptId() == null) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        QueryWrapper<User> wrapper = User.wrapper("id");
        wrapper.lambda().eq(User::getDeptId, user.getDeptId());
        List<User> list = userService.list(wrapper);
        List<Long> longs = CollUtil.map(list, MPCommonEntity::getId, true);
        return MsgUtil.success(longs);
    }
}
